import {apiBaseUrl} from "./config";

const request = (url, method, data) => {
  //进入加载提示...
  let opt = {
    url: apiBaseUrl + url,
    data: data,
    header: '',
    method: method,
    dataType: 'json',
    responseType: 'text',
  };
  if (method === 'get') {
    opt.header = {
      'content-type': 'application/json',
      'accessToken': wx.getStorageSync('token')
    }
  } else if (method === 'post') {
    opt.header = {
      'content-type': 'application/json',
      'accessToken': wx.getStorageSync('token')
    }
  } else if (method === 'put') {
    opt.header = {
      'content-type': 'application/json',
      'accessToken': wx.getStorageSync('token')
    }
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: opt.url,
      data: opt.data,
      header: opt.header,
      method: opt.method.toUpperCase(),
      dataType: opt.dataType,
      success: res => {
        if (res.data.httpCode == '200' || res.data.code == '200' || res.data.code == '403') {
          resolve(res.data);
        }else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
          reject(res.data);
        }
      },
      fail: res => {
        reject(res.data);
      },
      complete: res => {
        // resolve(res.data);
      }
    })
  })
};

export const getJSON = (url, data) => {
  return new Promise((resolve, reject) => {
    request(url, 'get', data).then(data => {
      resolve(data);
    }, err => {
      reject(err);
    })
  });
};

export const postJSON = (url, data) => {
  return new Promise((resolve, reject) => {
    request(url, 'post', data).then(data => {
        resolve(data);
    }, err => {
      reject(err);
    })
  })
};

export const putJSON = (url, data) => {
  return new Promise((resolve, reject) => {
    request(url, 'put', data).then(data => {
      resolve(data);
    }, err => {
      reject(err);
    })
  })
};
